import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:hitutor/UI/Home/OrderClass/DialogChooseTeacher.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyPage.dart';
import 'package:hitutor/Widget/Step.dart';

import '../Home.dart';

class OrderClass2 extends StatefulWidget {
  dynamic chooseTeacher;
  List<dynamic> TeacherList = [];
  Map<String, dynamic> params;
  List<dynamic> bookInfoList;
  Function() onNext;
  bool needSelectTeacher = false;
  static Map<String, dynamic> globalParams = {};

  OrderClass2(this.chooseTeacher, {required this.onNext, required this.TeacherList, required this.params, required this.bookInfoList}) {
    needSelectTeacher = chooseTeacher == null;
    globalParams = params;
  }

  @override
  State<StatefulWidget> createState() {
    return _OrderClass2();
  }
}

class _OrderClass2 extends State<OrderClass2> {
  ChooseTeacher() {
    showWheelDialog2(context, "", widget.TeacherList, "teacherName", (int index) {
      widget.chooseTeacher = widget.TeacherList[index];
      widget.params["teacherIdList"] = [widget.chooseTeacher["teacherId"]];
      setState(() {});
      getWorkDateList();
    });
  }

  getWorkDateList() {
    HttpGo(context).post("/Lesson/HitutorAPPGetCanBookList", widget.params, (data) {
      widget.bookInfoList = data["bookInfoList"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  // static int HIDE = 0;
  // static int ALL = 1;
  // int rightBtn = HIDE;
  //
  // rightClick() {
  //   rightBtn == HIDE ? Hide() : All();
  //   setState(() {});
  // }

  @override
  Widget build(BuildContext context) {
    return MyPage(
        "訂課",
        Container(
            padding: EdgeInsets.all(16),
            child: Column(children: [
              widget.needSelectTeacher
                  ? Container()
                  : Container(
                      margin: EdgeInsets.only(bottom: 16),
                      child: Chooser(widget.chooseTeacher["teacherName"], onTap: ChooseTeacher),
                    ),
              // Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
              //   widget.needSelectTeacher ? Container() : Chooser(widget.chooseTeacher["teacherName"], onTap: ChooseTeacher),
              //   TextBtn(rightBtn == HIDE ? "Hide" : "All",
              //       onTap: rightClick,
              //       height: 40,
              //       style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: MyColor.BlueHome, letterSpacing: 3))
              // ]),
              Expanded(
                  child: ListView.builder(
                      itemCount: widget.bookInfoList.length,
                      itemBuilder: (BuildContext context, int index) {
                        return ItemDayOrder(widget.bookInfoList[index],
                            hide: index != 0, needSelectTeacher: widget.needSelectTeacher, step1ChooserTeacher: widget.chooseTeacher);
                      })),
              Container(height: 8),
              Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                LastStep(onTap: () {
                  PageUtil().back(context);
                }),
                NextStep(onTap: () {
                  PageUtil().back(context);
                  widget.onNext();
                })
              ])
            ])),
        bgColor: MyColor.White);
  }
}

class Chooser extends StatelessWidget {
  String text;
  Function()? onTap;

  Chooser(this.text, {this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: onTap,
        child: Row(children: [
          Container(
              width: 120, child: Text("$text ", style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: MyColor.BlueHome))),
          LocalImage("arrowdown.png", width: 12)
        ]));
  }
}

class ItemDayOrder extends StatefulWidget {
  bool hide = true;
  bool needSelectTeacher;
  dynamic data;
  dynamic step1ChooserTeacher;

  ItemDayOrder(this.data, {required this.hide, required this.needSelectTeacher, this.step1ChooserTeacher});

  @override
  State<StatefulWidget> createState() {
    return _ItemDayOrder();
  }
}

class _ItemDayOrder extends State<ItemDayOrder> {
  SwitchClick() {
    widget.hide = !widget.hide;
    setState(() {});
  }

  // List<bool> isOrders = [false, true, false, false, false, false, false];

  @override
  Widget build(BuildContext context) {
    List<dynamic> canBookPeriodList = [];
    canBookPeriodList = widget.data["canBookPeriodList"] ?? [];
    int chooseNum = 0;
    for (var item in canBookPeriodList) {
      chooseNum += (item["lessonState"] != null ? 1 : 0);
    }

    return Container(
        color: MyColor.F4,
        margin: EdgeInsets.only(bottom: 8),
        child: Column(children: [
          GestureDetector(
              onTap: SwitchClick,
              behavior: HitTestBehavior.opaque,
              child: Container(
                  padding: EdgeInsets.all(8),
                  child: Row(children: [
                    Text("${widget.data["dateCode"]}", style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: MyColor.C58)),
                    // Text("(星期三)", style: TextStyle(fontSize: 13, color: MyColor.C58)),
                    Container(width: 16),
                    Visibility(
                        visible: chooseNum > 0, child: Text("已選堂數：$chooseNum", style: TextStyle(fontSize: 13, color: MyColor.OrangeTxt))),
                    Expanded(child: Container()),
                    RotatedBox(quarterTurns: widget.hide ? 0 : 2, child: LocalImage("arrowdown.png", width: 12))
                  ]))),
          Visibility(
              visible: !widget.hide,
              maintainState: true,
              child: ListView.builder(
                  itemCount: canBookPeriodList.length,
                  shrinkWrap: true,
                  padding: EdgeInsets.only(bottom: 8),
                  physics: NeverScrollableScrollPhysics(),
                  itemBuilder: (BuildContext context, int index) {
                    return ItemClassTime(canBookPeriodList[index], widget.needSelectTeacher, step1ChooseTeacher: widget.step1ChooserTeacher,
                        onOrder: (isOrder) {
                      // isOrders[index] = isOrder;
                    });
                  }))
        ]));
  }
}

class ItemClassTime extends StatefulWidget {
  dynamic orderInfo;

  // {
  // "classroomId": 2215306,
  // "teacherId": 2854,
  // "teacherName": "testTCH_Wing",
  // "purchaseOrderId": 318986,
  // "maxCount": 1,
  // "beginDateTime": "2022-02-11T12:00:00Z",
  // "endDateTime": "2022-02-11T13:30:00Z",
  // "displayBeginTime": "12:08",
  // "displayEndTime": "13:38",
  // "lessonState": 1
  // }
//   　lessonState:  1=學生訂課成功 (可以按[取消]按鈕)
//                  2=學生訂課，等待老師接受中(不可以按[取消]按鈕、不可再執行訂課)
//                  null/0=該時段，學生尚未訂課(可以按[訂課]按鈕)

  bool needSelectTeacher;
  Function(bool isOrder)? onOrder;
  dynamic step1ChooseTeacher;

  ItemClassTime(this.orderInfo, this.needSelectTeacher, {this.onOrder, this.step1ChooseTeacher});

  @override
  State<StatefulWidget> createState() {
    return _ItemClassTime();
  }
}

class _ItemClassTime extends State<ItemClassTime> {
  Cancel() {
    print("+++++++++++++++++++++++++++++++${widget.orderInfo}");
    HttpGo(context).post("/Lesson/GetCancelBookingMessage", {
      "studentId": OrderClass2.globalParams["studentId"],
      "classroomId": widget.orderInfo["classroomId"],
    }, (data) {
      showBtn2Dialog(context, data, "取消", () {}, "確定", () {
        ConfirmCancel();
      });
    }, (code, error) => showToast(error));
  }

  ConfirmCancel() {
    HttpGo(context).post("/Lesson/CancelBooking", {
      "studentId": OrderClass2.globalParams["studentId"],
      "classroomId": widget.orderInfo["classroomId"],
    }, (data) {
      Home.homeKey.currentState?.getHomePage(true);
      widget.orderInfo["lessonState"] = null;
      setState(() {});
      showToast("成功取消課程");
      widget.onOrder!(false);
      }, (code, error) => showToast(error));
  }

  OrderClick() {
    if (widget.needSelectTeacher) {
      getAllTeacher();
      return;
    }
    if (widget.step1ChooseTeacher != null)
      Order(widget.step1ChooseTeacher["teacherId"], widget.orderInfo["purchaseOrderId"], widget.step1ChooseTeacher["teacherName"]);
    else
      showToast("老師資料有誤");
  }

  getAllTeacher() {
    var params = {
      "studentId": OrderClass2.globalParams["studentId"],
      "lessonId": OrderClass2.globalParams["lessonId"],
      "plateformCode": OrderClass2.globalParams["plateformCode"],
      "timeZone": OrderClass2.globalParams["timeZone"],
      "beginDateTime": widget.orderInfo["beginDateTime"],
      "endDateTime": widget.orderInfo["endDateTime"]
    };
    HttpGo(context).post("/Lesson/HitutorAPPGetCanBookTeacherList", params, (data) {
      showWidgetDialog(
          context,
          DialogChooseTeacher(
              onOrderCallback: (teacherId, teacherName) {
                Order(teacherId, widget.orderInfo["purchaseOrderId"], teacherName);
              },
              teacherList: data["teacherList"] ?? []));
    }, (code, error) => showToast(error));
  }

  Order(var teacherId, var purchaseOrderId, var teacherName) {
    print(teacherId.toString() + teacherName.toString());
    HttpGo(context).post("/Lesson/Booking", {
      "purchaseOrderId": purchaseOrderId,
      "teacherId": teacherId,
      "beginDate": getUtcTime(DateTime.now()),
      "beginTime": widget.orderInfo["beginDateTime"],
      "endTime": widget.orderInfo["endDateTime"],
      "studentId": OrderClass2.globalParams["studentId"],
      "plateformCode": OrderClass2.globalParams["plateformCode"],
    }, (data) {
      widget.orderInfo["teacherId"] = data["lesson"]["teacherId"];
      widget.orderInfo["classroomId"] = data["lesson"]["classroomId"];
      widget.orderInfo["lessonState"] = data["lesson"]["lessonState"]; // 1=訂課成功  // 2=學生訂課，等待老師接受中(不可以按[取消]按鈕、不可再執行訂課)
      widget.orderInfo["teacherName"] = teacherName;
      setState(() {});
      if (widget.orderInfo["lessonState"] == 2) showToast("等待老師接受中");
      widget.onOrder?.call(true);

      //tod0
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    int state = widget.orderInfo["lessonState"] ?? 0;
    return Container(
        color: state > 0 ? Color(0xfffceedb) : MyColor.White,
        margin: EdgeInsets.fromLTRB(8, 4, 8, 4),
        padding: EdgeInsets.all(8),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            Expanded(
                child: Text("${widget.orderInfo["displayBeginTime"]} - ${widget.orderInfo["displayEndTime"]}",
                    style: TextStyle(fontSize: 14, color: state != 0 ? MyColor.C58 : MyColor.Black, fontWeight: FontWeight.bold))),
            Visibility(
                visible: state == 1,
                child: Button("取 消", fontSize: 12, height: 24, radius: 20, width: 60, bgColor: Color(0xffe9762f), onTap: Cancel)),
            Visibility(
                visible: state == 0,
                child: Button("訂 課", fontSize: 12, height: 24, radius: 20, width: 60, bgColor: Color(0xff5382b7), onTap: OrderClick))
          ]),
          Visibility(
              visible: state > 0,
              maintainState: true,
              child: Text("Teacher：${widget.orderInfo["teacherName"]}",
                  style: TextStyle(fontSize: 14, color: MyColor.C58, fontWeight: FontWeight.bold))),
        ]));
  }
}
